/**
 * LY.com Inc.
 * Copyright (c) 2004-2018 All Rights Reserved.
 */
package com.gitee.kamismile.stoneEureka.server.route;

import com.gitee.kamismile.stone.commmon.util.JsonUtil;
import com.gitee.kamismile.stoneEureka.pojo.RouteDefinition;
import com.gitee.kamismile.stoneEureka.server.GatewayConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static java.util.Collections.synchronizedMap;

/**
 * @author dong.li
 * @version $Id: RedisRouteDefinitionRepository, v 0.1 2018/10/18 10:06 dong.li Exp $
 */
@Component
public class RedisRouteDefinitionRepository {

    private final Map<String, RouteDefinition> routes = synchronizedMap(new LinkedHashMap<String, RouteDefinition>());

    @Autowired
    GatewayConstant gatewayConstant;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private final Logger logger = LoggerFactory.getLogger(getClass());

    public synchronized Map<String, RouteDefinition> getRouteDefinitions() {

        if (!routes.isEmpty()) {
            return routes;
        }

        List<RouteDefinition> routeDefinitions = new ArrayList<>();
        redisTemplate.opsForHash().values(gatewayConstant.getGatewayRoutes()).forEach(routeDefinition -> {
            RouteDefinition routeDef = JsonUtil.fromJson(routeDefinition.toString(), RouteDefinition.class);
            routeDefinitions.add(routeDef);
            routes.put(routeDef.getId(), routeDef);
        });

        return routes;
    }

    public Map<String, RouteDefinition> getRoutes() {
        return routes;
    }



}
